from functools import wraps

from flask import request,g
import jwt
import time
from flask import jsonify
from functools import wraps #类装饰器
#导入用户表：这个根据用户自己来
from apps.user.models import UserModel


JWT_SECRET_KEY = '$#%^&&*(DFHJKUTYGHF112312' #加密的盐
ALGORITHM = 'HS256' #加密算法

#生成token
def jwt_encode_token(user_id:int,time_out=7*24*60*60):
    payload = {
        'user_id': user_id,
        'iat': time.time(), #产生token时的时间戳
        'exp': time.time() + time_out #token过期时间戳
    }
    token = jwt.encode(payload, JWT_SECRET_KEY, algorithm=ALGORITHM)
    return token

#解析token
def jwt_decode_token(token):
    secret = JWT_SECRET_KEY
    payload = jwt.decode(token,secret,algorithms=ALGORITHM)
    return payload


#依赖于请求中间件先实现认证功能，再从request或g对象中取出用户信息
def authen_admin_required_middle(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        token = request.headers.get('token')
        if not token:
            token = request.cookies.get('token')
        if not token:
            return jsonify({'code': 410, 'msg': '没有携带token，请先登录'})
        try:
            payload = jwt_decode_token(token)
            user_id = payload.get('user_id')
            exp = payload.get('exp')
            obj = UserModel.query.filter_by(id=user_id).first()
            if not obj:
                return jsonify({'code': 410, 'msg': '当前用户不存在了'})
            if obj.role!='管理员':
                return jsonify({'code':400,'msg':'您当前没有权限操作'})
            now = time.time()
            if exp > now:
                return jsonify({'code': 410, 'msg': 'token过期，请重新登录'})

        except Exception as e:
            return jsonify({'code': 410, 'msg': 'token有问题，请先登录'})
        g.user = obj
        g.token = token
        ret = func(*args, **kwargs)
        return ret

    return wrapper


def login_required(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        token = request.headers.get('token')
        if not token:
            token = request.cookies.get('token')
        if not token:
            return jsonify({'code':410,'msg':'没有携带token，请先登录'})
        try:
            payload = jwt_decode_token(token)
            user_id = payload.get('user_id')
            exp = payload.get('exp')
            obj = UserModel.query.filter_by(id=user_id).first()
            if not obj:
                return jsonify({'code':410,'msg':'当前用户不存在了'})
            now = time.time()
            if exp < now:
                return jsonify({'code':410,'msg':'token过期，请重新登录'})

        except Exception as e:
            return jsonify({'code':410,'msg':'token有问题，请先登录'})
        g.user = obj
        g.token = token
        request.user = obj
        ret = func(*args,**kwargs)
        return ret
    return wrapper

if __name__ == '__main__':
    token = jwt_encode_token(78)
    print(token)
